package com.itheima.reggic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggic.dto.DishDto;
import com.itheima.reggic.mapper.CategoryMapper;
import com.itheima.reggic.mapper.DishMapper;
import com.itheima.reggic.pojo.Category;
import com.itheima.reggic.pojo.Dish;
import com.itheima.reggic.pojo.DishFlavor;
import com.itheima.reggic.service.CategoryService;
import com.itheima.reggic.service.DishFlavorService;
import com.itheima.reggic.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;


    @Transactional
    public boolean addWithFlavor(DishDto dishDto) {

        // 保存菜品数据到菜品表
        this.save(dishDto);
        Long dishId = dishDto.getId();
        dishDto.getFlavors().forEach(dishFlavor -> {
            // 设置保存的dishId
            dishFlavor.setDishId(dishId);
            // 保存口味到菜品口味表
            dishFlavorService.save(dishFlavor);
        });

        return true;
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    @Override
    public boolean updateByIdWithFlaover(DishDto dishDto) {
        // 保存菜品信息
        this.updateById(dishDto);

        // 删除之前菜品信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        // 由于dishDto中的flavor没有保存dishId，所以要手动添加一下
        dishDto.getFlavors().forEach(dishFlavor -> {
            // 设置保存的dishId
            dishFlavor.setDishId(dishDto.getId());
        });

        // 保存本次的菜品信息
        return dishFlavorService.saveBatch(dishDto.getFlavors());

    }
}
